from fastapi import APIRouter,Request,HTTPException,Depends
import string
import random
from utils.aliysms import AliyunSMSSender
from schemas.response import ResponseModel, UpdatedAvatarModel
from utils.cache import TLLRedis
from schemas.request import LoginModel,UpdateUsernameModel
from schemas.response import LoginedModel,UserListModel,UserModel

from utils.auth import AuthHandler
from services.user import UserServiceClient
from services.address import AddressServiceClient

from utils.status_code import get_http_code
from fastapi import UploadFile
from utils.alyoss import oss_upload_image

router=APIRouter(prefix='/user',tags=['用户'])

tll_redis=TLLRedis()
sms_sender=AliyunSMSSender()
auth_handler=AuthHandler()
user_service_client=UserServiceClient()
address_service_client=AddressServiceClient()

@router.get("/smscode/{mobile}",response_model=ResponseModel)
async def get_smscode(mobile:str):
    smscode=''.join(random.sample(string.digits,4))
    # await sms_sender.send_code("18019475322",smscode)
    await tll_redis.set_sms_code(mobile,smscode)
    print("smscode: ",smscode)
    return ResponseModel()

@router.post("/login",response_model=LoginedModel)
async def login(data:LoginModel):
    mobile=data.mobile
    smscode=data.smscode
    cached_data=await tll_redis.get_sms_code(mobile)
    if cached_data!=smscode:
        raise HTTPException(status_code=400,detail="验证码错误")
    user=await user_service_client.get_or_create_user_by_mobile(mobile)
    tokens=auth_handler.encode_login_token(user.id)
    await tll_redis.set_refresh_token(user.id,tokens['refresh_token'])
    return {
        'user':user,
        'access_token':tokens['access_token'],
        'refresh_token':tokens['refresh_token']
    }

@router.get('/logout',response_model=ResponseModel)
async def logout(user_id:int=Depends(auth_handler.auth_access_dependency)):
    await tll_redis.delete_refresh_token(user_id)
    return ResponseModel()
        
@router.get('/access/token')
async def get_access_token(user_id:int=Depends(auth_handler.auth_access_dependency)):
    return {
        "message":"accesstoken验证成功",
        'user_id':user_id
    }
    
@router.get('/refresh/token')
async def get_refresh_token(user_id:int=Depends(auth_handler.auth_refresh_dependency)):
    access_token=auth_handler.encode_update_token(user_id)
    return access_token

@router.put('/update/username',response_model=ResponseModel)
async def update_username(data:UpdateUsernameModel,user_id:int=Depends(auth_handler.auth_access_dependency)):
    username=data.username
    if not username:
        raise HTTPException(status_code=400,detail="用户名不能为空")
    await user_service_client.update_username(user_id,username)
    return ResponseModel()

@router.put('/update/password',response_model=ResponseModel)
async def update_password(request:Request,user_id:int=Depends(auth_handler.auth_access_dependency)):
    data=await request.json()
    password=data.get('password')
    if not password:
        raise HTTPException(status_code=400,detail="密码不能为空")
    await user_service_client.update_password(user_id,password)
    return ResponseModel()

@router.put('/update/avatar',response_model=UpdatedAvatarModel)
async def update_avatar(file:UploadFile,
                        user_id:int=Depends(auth_handler.auth_access_dependency)):
    avatar_url=await oss_upload_image(file)
    if avatar_url:
        await user_service_client.update_avatar(user_id,avatar_url)
        return UpdatedAvatarModel(file_url=avatar_url)
    raise HTTPException(status_code=400,detail="头像上传失败")

@router.get('/mine',response_model=UserModel)
async def get_my_info(user_id:int=Depends(auth_handler.auth_access_dependency)):
    response=await user_service_client.get_user_by_id(user_id)
    return response

@router.get('/{mobile}',response_model=UserModel)
async def get_mine_info(mobile:str,user_id:int=Depends(auth_handler.auth_access_dependency)):
    response=await user_service_client.get_user_by_mobile(mobile=mobile)
    return response

@router.get('/list',response_model=UserListModel)
async def get_user_list(page:int=1,page_size:int=10,user_id:int=Depends(auth_handler.auth_access_dependency)):
    response=await user_service_client.get_user_list(page,page_size)
    return response

@router.post('/verify',response_model=ResponseModel)
async def verify_user(data:Request):
    data=await data.json()
    mobile=data.get('mobile')
    password=data.get('password')
    response=await user_service_client.verify_user(mobile,password)
    if response.result!=1:
        raise HTTPException(status_code=get_http_code(response.result),detail=response.message)
    tokens=auth_handler.encode_login_token(response.user_info.id)
    return {
        'user':response.user_info,
        'access_token':tokens['access_token'],
        'refresh_token':tokens['refresh_token']
    }



# 添加一个空行来确保文件正确结束
